import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PropertyType;
import javax.jcr.Session;
import javax.jcr.query.QueryManager;
import javax.jcr.version.Version;
import javax.jcr.version.VersionHistory;
import javax.jcr.version.VersionIterator;

import org.apache.jackrabbit.value.StringValue;

import sun.net.www.MimeTable;

import com.atjava.jcrt.BaseInfo;
import com.atjava.jcrt.JcrtSession;
import com.atjava.jcrt.JcrtSessionFactory;
import com.atjava.jcrt.core.ContentData;
import com.atjava.jcrt.core.ItemType;
import com.atjava.jcrt.core.SystemProperty;
import com.atjava.jcrt.core.query.ConditionData;
import com.atjava.jcrt.core.query.Query;
import com.atjava.jcrt.core.transaction.XmlServices;
import com.atjava.jcrt.core.transaction.XmlTransactionException;
import com.atjava.jcrt.repository.Provider;
import com.atjava.jcrweb.info.ContentInfo;
import com.atjava.jcrweb.info.DirectoryInfo;
import com.atjava.jcrweb.info.FileInfo;
import com.atjava.jcrweb.info.UserInfo;
import com.atjava.jcrweb.manager.DirectoryManager;
import com.atjava.jcrweb.manager.UserManager;

/**
 *
 * AtJava source-code is licensed under the LGPL.
 * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
 * When copying, adapting, or redistributing this document in keeping with the guidelines above,
 * you are required to provide proper attribution to obinary.
 * If you reproduce or distribute the document without making any substantive modifications to its content,
 * please use the following attribution line:
 *
 * Copyright 2007 Atjava.com Ltd. (http://www.atjava.com) All rights reserved.
 *
 */

public class TestRo {
	
	private Provider provider = null;
	private Session session = null;
	private JcrtSession jsession = null;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TestRo t = new TestRo();
		t.setPath();
		try{
			t.init();
			//t.showUsers();
			t.addUser();
			//t.addNode();
			//t.showFiles();
			//t.addFolder();
			//t.addDir();
			//t.queryNode();
			//t.queryNode2();
			//t.addContent();
			//t.viewHisotry();
			//t.test();
			//System.out.println(t.changetToNpPath("aaa/bbb/ccc/ddd"));
		}catch(Exception e){
			e.printStackTrace();
		}
		System.exit(0);
	}
	private void addUser() throws Exception{
		UserInfo userInfo = new UserInfo();
		userInfo.setUserCode("biggie");
		userInfo.setUserName("王洪斌");
		userInfo.setPassword("summer");
		userInfo.setPermissionDirPath("/1/14,/2/18");
		userInfo.setNote("1111111111111");
		
		UserManager manager = UserManager.getInstance();
		manager.updateUser(userInfo);
	}
	private void showUsers() throws Exception {
		UserManager manager = UserManager.getInstance();
		List list = manager.getAllUsers();
		for(int i=0;i<list.size();i++){
			UserInfo info = (UserInfo)list.get(i);
			System.out.println(info.toXmlString());
		}
	}
	private void showFiles() throws Exception{
		List list = jsession.getChildren(FileInfo.class, "/");
		for(int i=0;i<list.size();i++){
			FileInfo info=(FileInfo)list.get(i);
			System.out.println(info.getId());
			System.out.println(info.getFileName());
			
		}
		List list2 = jsession.getChildren(ContentInfo.class, "/");
		for(int i=0;i<list2.size();i++){
			ContentInfo info=(ContentInfo)list2.get(i);
			System.out.println(info.getId());
			System.out.println(info.getName());
			System.out.println(info.getFile2Name());
		}
	}
	private void addDir() throws Exception{
		
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());

		DirectoryManager manager = DirectoryManager.getInstance();
		DirectoryInfo info = new DirectoryInfo();
		info.setDatetime(c);
		info.setName("xxxx dir33");
		info.setNote("xxxx note33");
		info.setCreaterCode("xx");
		
		manager.createDirectory(info, "/25");
		
		DirectoryInfo info2 = (DirectoryInfo) jsession.load(DirectoryInfo.class, "/1/"+info.getId());
		
		System.out.println(info2.getName());
		System.out.println(info2.getNote());
		System.out.println(info2.getRelPath());
	}
	private void setPath(){
		Properties props = System.getProperties();
		//props.setProperty("webapp_path", "D:/eclipse/workspace/AtJavajcrWeb/WebContent");
		props.setProperty("webapp_path", "D:/eclipse/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/AtJavajcrWeb");
		System.setProperties(props);
		//SystemProperty.SYSTEM_REALPATH = "D:/MyProject/AtJavajcrWeb/WebContent";
	//	SystemProperty.SYSTEM_REALPATH = "D:/eclipse/workspace/AtJavajcrWeb/WebContent";
	}
	private void queryNode2() throws Exception{
		QueryManager qm = session.getWorkspace().getQueryManager();
		javax.jcr.query.Query query = qm.createQuery("/dir:25/[jcr:contains(@createrCode,'xx')]",javax.jcr.query.Query.XPATH);
		NodeIterator ni = query.execute().getNodes();
		while (ni.hasNext()) {
			Node nv = ni.nextNode();
			if(nv.getPath().indexOf("jcr:system")==-1){
				
				//System.out.println(nv.getProperty("id").getLong());
				//System.out.println(nv.getProperty("name").getString());
				System.out.println(nv.getPath());	
			}
		}
	}
	private void queryNode() throws Exception{
		ConditionData data = new ConditionData();
		data.setCondition("createrCode", "xx", ConditionData.CONDITION_EQUAL);
		//data.setCondition("note", "xxxx", ConditionData.CONDITION_CONTAINS);
		//data.setCondition("id", "1", ConditionData.CONDITION_EQUAL);
		
		Query query = jsession.createQuery(ContentInfo.class, "/", data);
		List results = query.getDefaultResults();
		System.out.println("Query size ="+results.size());
		for(int i=0;i<results.size();i++){
			ContentInfo info = (ContentInfo)results.get(i);
			System.out.println(info.getId());
			System.out.println(info.getName());
			System.out.println(info.getPath());
			System.out.println(info.getRelPath());
		}
		
	}
	private void addNode() throws Exception{
		Node root = session.getRootNode();
		Node dirNode = root.getNode("dir:25");
		Node test = dirNode.addNode("cnt:1");
		test.setProperty("createrCode", new StringValue("xx"));
		test.setProperty("name", new StringValue("123123213"));
		test.addMixin("mix:versionable");
		session.save();
		test.checkin();
		getNode();
	}
	private void delNode() throws Exception {
		Node root = session.getRootNode();
		
		Node test3 = root.getNode("cnt:test");
		test3.remove();
		session.save();
	  
	}
	private void getNode() throws Exception {
		Node root = session.getRootNode();
		
		Node dirNode = root.getNode("dir:25");
		NodeIterator ni = dirNode.getNodes();
		while (ni.hasNext()) {
			Node nv = ni.nextNode();
			if(nv.getPath().indexOf("jcr:system")==-1){
				
				//System.out.println(nv.getProperty("id").getLong());
				//System.out.println(nv.getProperty("name").getString());
				System.out.println(nv.getPath());	
			}
		}
	}
	private void addContentFile1() throws Exception{
		Node root = session.getRootNode();
		Node test = root.addNode("cnt:test");
		File file = new File("C:/shuxing.jpg");
		MimeTable mt = MimeTable.getDefaultTable();
		String mimeType = mt.getContentTypeFor(file.getName());
		if (mimeType == null) mimeType = "application/octet-stream";

		Node fileNode = test.addNode(file.getName(), "nt:file");
		Node resNode = fileNode.addNode("jcr:content", "nt:resource");
		resNode.setProperty("jcr:mimeType", mimeType);
		resNode.setProperty("jcr:encoding", "");
		resNode.setProperty("jcr:data", new FileInputStream(file));
		Calendar lastModified = Calendar.getInstance();
		lastModified.setTimeInMillis(file.lastModified());
		resNode.setProperty("jcr:lastModified", lastModified);

		test.addMixin("mix:versionable");
		
		session.save();
		test.checkin();
	}
	
	private void addContent() throws Exception{
		Node root = session.getRootNode();
		Node test = root.addNode("cnt:test");
		test.setProperty("p1", new StringValue("11"));
		test.setProperty("p2", new StringValue("22"));
		File file = new File("C:/shuxing.jpg");
		test.setProperty("jcr:data2", new FileInputStream(file));
			
		test.addMixin("mix:versionable");
		
		session.save();
		test.checkin();
		addContent2();
	}
	private void addContent2() throws Exception{
		
		Node root = session.getRootNode();
		Node test = root.getNode("cnt:test");
		test.checkout();
		test.setProperty("p1", new StringValue("1122"));
		test.setProperty("p2", new StringValue("2222"));
		test.setProperty("p2", new StringValue("222211111111"));
	
		test.addMixin("mix:versionable");
	
		session.save();
		test.checkin();
		
	}

	public void viewHisotry() throws Exception{
		Node root = session.getRootNode();
		Node test = root.getNode("cnt:test");
		VersionHistory vh = test.getVersionHistory();
		VersionIterator vi = vh.getAllVersions();

		vi.skip(1);
		while (vi.hasNext()) {
				 Version v = vi.nextVersion();
				 NodeIterator ni = v.getNodes();

				 while (ni.hasNext()) {
				  Node nv = ni.nextNode();
				  System.out.println("Version: " +
				  v.getCreated().getTime());
				  
				  System.out.println(nv.getProperty("p1").getString());
				  System.out.println(nv.getProperty("p2").getString());
				  
				  if(nv.getProperty("jcr:data2")!=null && nv.getProperty("jcr:data2").getType() == PropertyType.BINARY){
					  FileOutputStream out = new FileOutputStream(new File("C:/shuxing2.jpg"));
					  InputStream in = nv.getProperty("jcr:data2").getStream();
					  byte[] b = new byte[1024];
					  while(in.read(b)!=-1){
						  out.write(b);
					  }
					  out.close();
				  }
				 }

		}

	}

	private void init() throws Exception{
		JcrtSessionFactory factory = JcrtSessionFactory.getInstance();
		jsession = factory.openJcrtSession();
		XmlServices xmlServices = XmlServices.getInstance();
		this.provider = factory.getProvider();
		session = this.provider.getSession(xmlServices.getXmlJcrtInfo().getXmlJcrtInfoDetail(ContentInfo.class).getWorkspacename());
	}
	
}
